package com.beyond.trace.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beyond.trace.domain.ScreenConfigure;
import com.beyond.trace.domain.TraceLand;
import com.beyond.trace.requestVo.ScreenConfigureAddReq;
import com.beyond.trace.service.ScreenConfigureService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BizException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import kotlin.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName: ScreenConfigureController
 * @author: z越
 * @date: 2024/4/7  11:34
 * @description
 */
@RestController
@RequestMapping("/screen/configure")
@Api(tags = "大屏配置管理")
@RequiredArgsConstructor
public class ScreenConfigureController extends BaseController {
    private final ScreenConfigureService screenConfigureService;
    private final String ON_LINE="online";

    @GetMapping("/list")
    @ApiOperation("列表查询")
    @ApiImplicitParam(name = "model",value = "所属模块",dataType = "String",dataTypeClass = String.class)
    public TableDataInfo list(String model){
        startPage();
        LambdaQueryWrapper<ScreenConfigure> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(model)){
            queryWrapper.eq(ScreenConfigure::getModule,model);
        }
        queryWrapper.orderByDesc(ScreenConfigure::getCreateTime);
        List<ScreenConfigure> list = this.screenConfigureService.list(queryWrapper);
        return getDataTable(list);
    }

    @GetMapping("/{id}")
    @ApiOperation("查询详情")
    public AjaxResult getInfo(@PathVariable Long id){
        if (Objects.isNull(id)){
            return AjaxResult.error("id不能为空");
        }
        ScreenConfigure po = this.screenConfigureService.getById(id);
        return AjaxResult.success(po);
    }

    @GetMapping("/by/params")
    @ApiOperation("通过模块或点位查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "model",value = "所属模块",dataType = "String",dataTypeClass = String.class),
            @ApiImplicitParam(name = "point",value = "所属点位",dataType = "String",dataTypeClass = String.class)
    })
    public AjaxResult getInfo(@RequestParam String model,String point){
        LambdaQueryWrapper<ScreenConfigure> wrapper = new LambdaQueryWrapper<ScreenConfigure>()
                .eq(ScreenConfigure::getModule,model).eq(ScreenConfigure::getState,ON_LINE);
        if (StringUtils.isNotEmpty(point)){
            wrapper.eq(ScreenConfigure::getPointPosition,point);
        }
        ScreenConfigure po = this.screenConfigureService.getOne(wrapper);
        return AjaxResult.success(po);
    }


    @Log(title = "新增大屏配置", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增")
    public AjaxResult add(@RequestBody @Validated ScreenConfigureAddReq req){
        checkData(req,null);
        ScreenConfigure po = req.toPo();
        po.setOperationTime(new Date());
        po.setCreateTime(new Date());
        po.setState("");
        return AjaxResult.success(this.screenConfigureService.save(po));
    }

    @Log(title = "修改大屏配置", businessType = BusinessType.UPDATE)
    @PutMapping("/edit/{id}")
    @ApiOperation("修改")
    public AjaxResult edit(@PathVariable Long id ,@RequestBody @Validated ScreenConfigureAddReq req){
        ScreenConfigure oldPo = this.screenConfigureService.getById(id);
        checkData(req,id);
        if (Objects.isNull(oldPo)){
            return AjaxResult.error("此id未查询到数据，请核对后重新操作！！");
        }
        if (ON_LINE.equals(oldPo.getState())){
            return AjaxResult.error("当前数据已发布，请先下架后重新操作！！");
        }
        ScreenConfigure po = req.toOldPo(oldPo);
        po.setId(id);
        po.setOperationTime(new Date());
        return AjaxResult.success(this.screenConfigureService.updateById(po));
    }

    @Log(title = "上架大屏配置", businessType = BusinessType.UPDATE)
    @PutMapping("/online/{id}")
    @ApiOperation("上架")
    public AjaxResult online(@PathVariable Long id){
        ScreenConfigure po = this.screenConfigureService.getById(id);
        if (Objects.isNull(po)){
            return AjaxResult.error("此id未查询到数据，请核对后重新操作！！");
        }
        if (ON_LINE.equals(po.getState())){
            return AjaxResult.error("当前数据已发布，请核对后重新操作");
        }
        po.setState(ON_LINE);
        po.setOperationTime(new Date());
        return AjaxResult.success(this.screenConfigureService.updateById(po));
    }

    @Log(title = "下架大屏配置", businessType = BusinessType.UPDATE)
    @PutMapping("/offline/{id}")
    @ApiOperation("下架")
    public AjaxResult offline(@PathVariable Long id){
        ScreenConfigure po = this.screenConfigureService.getById(id);
        if (Objects.isNull(po)){
            return AjaxResult.error("此id未查询到数据，请核对后重新操作！！");
        }
        String state = "offline";
        if (state.equals(po.getState())){
            return AjaxResult.error("当前数据已下架，请核对后重新操作");
        }
        po.setState(state);
        po.setOperationTime(new Date());
        return AjaxResult.success(this.screenConfigureService.updateById(po));
    }

    @Log(title = "删除大屏配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除大屏配置")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return AjaxResult.success(this.screenConfigureService.remove(new LambdaQueryWrapper<ScreenConfigure>()
                .in(ScreenConfigure::getId,Arrays.asList(ids))));
    }

    private void checkData(ScreenConfigureAddReq req,Long id){
        LambdaQueryWrapper<ScreenConfigure> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScreenConfigure::getModule,req.getModel());
        if (StringUtils.isNotEmpty(req.getPointPosition())){
            wrapper.eq(ScreenConfigure::getPointPosition,req.getPointPosition());
        }
        ScreenConfigure po = this.screenConfigureService.getOne(wrapper);
        if (Objects.nonNull(po) && Objects.nonNull(id) && !po.getId().equals(id)){
            throw new BizException("相同模块或相同点位数据已存在，请核对后重新操作");
        }
    }
}
